package com.bw.module_service.repository

import com.bw.module_service.http.ServiceApi
import com.bw.module_service.ui.AnnouncementForm
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject

class ServiceRepository @Inject constructor() {
    @Inject
    lateinit var api:ServiceApi

    //车位
    fun getParkSpace(spaceType: String) = flow {
        emit(api.getParkSpace(spaceType))
    }.flowOn(Dispatchers.IO)

    //添加车位
    fun addParkSpace(body: RequestBody) = flow {
        emit(api.addParkSpace(body))
    }.flowOn(Dispatchers.IO)

    //删除车位
    fun deleteParkSpace(id:Int) = flow {
        emit(api.deleteParkSpace(id))
    }.flowOn(Dispatchers.IO)

    //根据id获取车辆
    fun getCar(id:Int) = flow {
        emit(api.getCar(id))
    }.flowOn(Dispatchers.IO)

    //根据车牌获取车辆
    fun byNumGetCar(licensePlate: String) = flow {
        emit(api.byNumGetCar(licensePlate))
    }.flowOn(Dispatchers.IO)

    //添加车辆
    fun addCar(body: RequestBody) = flow {
        emit(api.addCar(body))
    }.flowOn(Dispatchers.IO)

    //删除车辆
    fun deleteCar(id:Int) = flow {
        emit(api.deleteCar(id))
    }.flowOn(Dispatchers.IO)

    //获得省份简码
    fun getProvinces() = flow {
        emit(api.getProvinces())
    }.flowOn(Dispatchers.IO)

    //修改车辆
    fun updateCar(id:Int,body: RequestBody) = flow {
        emit(api.updateCar(id,body))
    }.flowOn(Dispatchers.IO)


    fun getPatrolPoints() = flow {
        emit(api.getPatrolPoints())
    }.flowOn(Dispatchers.IO)

    //签到
    fun getSignInfo(userId: Int) = flow {
        emit(api.getSignInfo(userId))
    }.flowOn(Dispatchers.IO)


    fun getSign(map:Map<String,Any>) = flow {
        val body = Gson().toJson(map)
        val requestBody = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),body)
        emit(api.getSign(requestBody))
    }.flowOn(Dispatchers.IO)

    //添加点位
    fun addPolling(body: RequestBody) = flow {
        emit(api.addPolling(body))
    }.flowOn(Dispatchers.IO)

    fun getPollingDetailById(id: Int) = flow {
        emit(api.getPollingDetailById(id))
    }.flowOn(Dispatchers.IO)

    fun addVip(body: RequestBody) = flow {
        emit(api.addVip(body))
    }.flowOn(Dispatchers.IO)

    //公告
    fun getAnnouncement() = flow {
        emit(api.getAnnouncement())
    }.flowOn(Dispatchers.IO)
    //发布公告
    fun postAnnouncement(map: AnnouncementForm) = flow {
        val json = Gson().toJson(map)
        val request = RequestBody.create("application/json".toMediaTypeOrNull(), json)
        emit(api.postAnnouncement(request))
    }.flowOn(Dispatchers.IO)

    
    fun getVipInfo(userId: Int) = flow {
        emit(api.getVipInfo(userId))
    }.flowOn(Dispatchers.IO)

    fun getTaskList() = flow {
        emit(api.getTaskList())
    }.flowOn(Dispatchers.IO)
}